//开启服务
package server

import (
	"fmt"
	"github.com/xiaoqinghong/super_daemon/config"
	"github.com/xiaoqinghong/super_daemon/core"
	coreP "github.com/xiaoqinghong/super_daemon/core/program"
	"github.com/xiaoqinghong/super_daemon/handler"
	"net/http"
	"strings"
)

//运行http服务，用于接收指令
func runHttpServer(killChan chan<- error) {
	fmt.Println("http server run")
	httpServer := http.NewServeMux()
	httpServer.HandleFunc("/http/cmd", handler.HandlePost)
	httpServer.HandleFunc("/http/get", handler.HandleGet)
	killChan <- http.ListenAndServe("127.0.0.1:9002", httpServer)
}

//运行守护进程
func runDaemonServer() {
	fmt.Println("daemon server run")
	daemonServer := core.Instance()
	programs := config.Config().Programs
	errCh := make(chan error, len(programs))
	for _, program := range programs {
		go func(p coreP.IProgram, ch chan<- error) {
			ch <- daemonServer.ExecProgram(p)
		}(program, errCh)
	}
	strBuilder := strings.Builder{}
	for i := 0; i < len(programs); i++ {
		if err := <-errCh; err != nil {
			strBuilder.WriteString(err.Error())
			strBuilder.WriteString("\n")
		}
	}
	fmt.Println(strBuilder.String())
}

//执行服务
func Run() (err error) {
	finishChan := make(chan error)
	go runHttpServer(finishChan)
	go runDaemonServer()
	select {
	case err = <-finishChan:
		break
	}
	return
}
